package com.yc.exam.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.exam.entity.Exam;
import com.yc.exam.entity.User;
import com.yc.exam.service.ICourseService;
import com.yc.exam.service.IExamService;
import com.yc.exam.service.IUserService;
import com.yc.exam.vo.AnswerSheetVo;
import com.yc.exam.vo.ExamVo;
import io.swagger.annotations.AuthorizationScope;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;
import java.util.List;

/**
 * 前端控制器
 *
 * @author 王妍
 * @since 2022-03-23
 */
@RestController
@RequestMapping("/exam/exam")
public class ExamController {

  @Autowired private IExamService examService;
  @Autowired private ICourseService courseService;

  @Autowired private IUserService userService;


  /** 分页查询 */
  @GetMapping("/page")
  public Page<ExamVo> getPage(Page<ExamVo> examPage, ExamVo exam) {
    return examService.pageVo(examPage, exam);
  }

  @GetMapping("student")
  public Page<ExamVo> getPageByStudent(Page<ExamVo> examPage, ExamVo exam, Principal principal) {
    final String studentUserName = principal.getName();
    return examService.getPageByStudentName(examPage, exam, studentUserName);
  }

  @GetMapping("teacher")
  public Page<ExamVo> getPageByTeacher(Page<ExamVo> examPage, ExamVo exam, Principal principal) {
    final String teacherUserName = principal.getName();
    return examService.getPageByStudentName(examPage, exam, teacherUserName);
  }

  @PostMapping
  public boolean saveOrUpdate(@RequestBody ExamVo exam) {
    return examService.saveOrUpdate(exam);
  }

  @DeleteMapping
  public boolean deleteByIds(@RequestBody Long[] ids) {
    return examService.removeBatchByIds(Arrays.asList(ids));
  }

  /** 完成试卷生成及阅卷系统 */
  @PostMapping("finishUpExam")
  public Long finishUpExam(Principal principal, @RequestBody AnswerSheetVo answerSheetVo ) {
    final String username = principal.getName();
    final User user = userService.loadUserByUserName(username);
    return examService.finishUpExam(user.getId(),answerSheetVo);
  }

  @GetMapping("{courseId}")
  public ExamVo load(@PathVariable Long courseId) {
    final Exam exam = examService.getById(courseId);
    final ExamVo examVo = new ExamVo();
    BeanUtils.copyProperties(exam, examVo);
    examVo.setCourseName(courseService.getById(exam.getCourseId()).getName());
    return examVo;
  }

  /**
   * 通过一些条件生成考试
   *
   * @param examVo
   * @return
   */
  @PostMapping("auto")
  public Long autoGenerateTestPaper(@RequestBody ExamVo examVo) {
    return examService.auto(examVo);
  }


  @PostMapping("/send/{examId}")
  public void send(@PathVariable Long examId,@RequestBody Long[] ids){
    examService.send(examId,ids);
  }
}
